import React, { ChangeEvent, memo, useContext, useMemo } from 'react';

import { AutoComplete, Input } from 'antd';


import { IDictionaryTypeSearch } from '@/pages/SystemController/DictionaryTreeController/type';

import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';


import { DictionaryContext } from '@/pages/SystemController/DictionaryTreeController/hooks';

export const DictionaryTypeSearch: React.FC<IDictionaryTypeSearch> = memo(
  ({ reloadTree }) => {
    const {
      searchValue,
      treeData,
      reloadTableDataSource,
      commonDispatch,
    } = useContext(DictionaryContext);
    const tileArray: Record<string, any>[] = [];
    const loopArray = (array: any[]): Record<string, any>[] => {
      array?.forEach((item) => {
        if (item?.children) {
          loopArray(item?.children);
        }
        tileArray.push(item);
      });
      return tileArray;
    };

    const autoOption = useMemo(() => {
      let option: Record<string, any>[] = [];
      const tileTreeData = (data: Record<string, any>[]) => {
        data?.forEach((item) => {
          if (item?.children && item?.children?.length > 0) {
            tileTreeData(item?.children);
          }
          if (item?.name?.includes(searchValue)) {
            // const name = item?.name;
            // const nameLength = name?.length;
            // const select = name?.search(searchValue);
            // const searchLength = searchValue?.length;
            // const afterStr = name?.slice(0, select);
            // const selectStr = searchValue;
            // const beforeStr = name?.slice(select + searchLength, nameLength);
            option.push({
              value: item?.name,
              key: item?.id,
              // label: (
              //   <div>
              //     <span>{afterStr}</span>
              //     <span style={{ color: '#f50' }}>{selectStr}</span>
              //     <span>{beforeStr}</span>
              //   </div>
              // ),
            });
          }
        });
      };
      tileTreeData(treeData);
      return option;
    }, [treeData, searchValue]);

    const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
      commonDispatch({
        type: 'edit-searchValue',
        payload: e.target.value,
      });
    };

    const onAutoSelect = (value: string, option: any) => {
      const promise = new Promise((resolve) => {
        const optionId = option?.key;
        const targetNode = loopArray(treeData)?.find((i) => i?.id === optionId);
        commonDispatch({
          type: 'edit-searchValue',
          payload: value,
        });
        commonDispatch({
          type: 'edit-selectKeys',
          payload: [option?.key],
        });
        commonDispatch({
          type: 'edit-expandedKeys',
          payload: [targetNode?.pID],
        });
        commonDispatch({
          type: 'edit-autoExpandParent',
          payload: true,
        });
        resolve(optionId);
      });
      promise.then((res: any) => {
        if (res) {
          reloadTableDataSource(res);
        }
      });
    };

    const onReloadTree = () => {
      const promise = new Promise((resolve) => {
        commonDispatch({
          type: 'remove-all-state', // 清空state
        });
        resolve(true);
      });

      promise.then((res) => {
        if (res) {
          reloadTree();
        }
      });
    };

    return (
      <AutoComplete
        style={{
          width: '100%',
          padding: '0rem 16px',
        }}
        options={autoOption}
        onSelect={onAutoSelect}
        dropdownMatchSelectWidth={true}
      >
        <Input
          placeholder={'按类型名称搜索'}
          suffix={<SearchOutlined />}
          onChange={onInputChange}
          addonAfter={<ReloadOutlined onClick={onReloadTree} />}
        />
      </AutoComplete>
    );
  },
);
